package com.hangxintong.common.config;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.auth0.jwt.JWT;
import com.hangxintong.common.base.dto.HeaderDto;
import com.hangxintong.common.base.entity.LmUser;
import com.hangxintong.common.base.service.UserService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author lvyanfei
 */
@Component
public class HeaderHolder {
    @Resource
    UserService userService;
    public HeaderDto getHeader(){
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        HeaderDto headerDto = new HeaderDto();
        headerDto.setToken(request.getHeader("token"));
        if(ObjectUtil.isNotNull(request.getHeader("token"))){
            String account = JWT.decode(request.getHeader("token")).getAudience().get(0);
            LmUser lmUser = userService.findByMobile(account);
            headerDto.setUser(lmUser);
        }
        headerDto.setXID(Convert.toStr(request.getHeader("xId")));
        headerDto.setXType(Convert.toLong(request.getHeader("xType")));
        return headerDto;
    }
}
